const fs = require('fs');
const path = require('path');
const XLSX = require('xlsx');

const inputDir = path.join(__dirname, 'output-table');
const outputDir = path.join(__dirname, 'excel');

if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir);
}

function convertMdTableToExcel(mdContent) {
  const lines = mdContent.split('\n').filter(line => line.trim() !== '');
  const tableData = [];

  lines.forEach(line => {
    if (line.startsWith('|') && !line.includes('---')) {
      const row = line
        .split('|')
        .map(cell => cell.trim())
        .filter(cell => cell !== '');
      tableData.push(row);
    }
  });

  return tableData;
}

function saveAsExcel(data, filename) {
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, path.join(outputDir, filename));
}

async function main() {
  const mdFiles = fs.readdirSync(inputDir).filter(file => file.endsWith('.md'));

  mdFiles.forEach(file => {
    const mdContent = fs.readFileSync(path.join(inputDir, file), 'utf8');
    const tableData = convertMdTableToExcel(mdContent);
    const excelFilename = file.replace('.md', '.xlsx');
    saveAsExcel(tableData, excelFilename);
  });
}

// 导出main函数
module.exports = { main };

// 如果直接运行此文件，则执行main函数
if (require.main === module) {
  main();
}